import ansiEscapes from 'ansi-escapes';

import { Key, Prompt } from "./Prompt.js";
import chalk from 'chalk';

export interface TextPromptOptions  {
    type: 'text'
    name: string
    message: string
}

function isNonPrintableChar(char: string) {
    return /^[\x00-\x1F\x7F]$/.test(char);
}

export class TextPrompt extends Prompt {
    out = process.stdout
    // 通过 cursor 记录光标位置，删除的时候用 slice 截取字符串
    cursor = 0
    constructor(private options: TextPromptOptions) {
        super();
    }
    onKeyInput(str: string, key: Key) {
        if (key.name === 'backspace') {
            this.cursor --;
            this.value = this.value.slice(0, this.cursor);
        }

        // 如果输入的是一些控制字符，比如 ESC 键等，就不做处理
        if(!isNonPrintableChar(str)) {
            this.value += str;
            this.cursor ++;
        }

        this.render();
    }

    render() {
        // 清除当前行
        this.out.write(ansiEscapes.eraseLine);
        // 回到当前行的开头
        this.out.write(ansiEscapes.cursorTo(0));
        // 打印问题
        this.out.write([
            chalk.bold(this.options.message),
            chalk.gray('›'),
            ' ',
            chalk.blue(this.value)
        ].join(''))
        // 去打印错误之前，我们先把光标位置 save 了
        this.out.write(ansiEscapes.cursorSavePosition)
        // 然后光标下移一行、回到开头
        this.out.write(ansiEscapes.cursorDown(1) + ansiEscapes.cursorTo(0))
        // 如有错误，打印错误
        if(this.value === '') {
            this.out.write(chalk.red('请输入名字'))
        } else {
            this.out.write(ansiEscapes.eraseLine)
        }
        // 打印完之后再 restore
        this.out.write(ansiEscapes.cursorRestorePosition)
    }

}